package org.fire.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import android.util.Log;

/**
 * 2G透传上传数据： FA[11个字节]F5
 * 
 * 控制端：^{...}$
 * 
 * @author DLX
 *
 */
public class MinaMessageDecoder extends CumulativeProtocolDecoder {
	private static final String TAG = "MinaMessageDecoder";
	
	private static byte[] JSON_STARTS = "^{".getBytes();
	private static byte[] JSON_ENDS = "}$".getBytes();

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		int remaining = in.remaining();
		// json?
		if (4 <= remaining) {
			if (JSON_STARTS[0] == in.get(0) && JSON_STARTS[1] == in.get(1)) {
				int index = -1;
				for (int i = 2; i < remaining; i++) {
					if (in.get(i) == JSON_ENDS[0] && i < remaining - 1
							&& in.get(i + 1) == JSON_ENDS[1]) {
						index = i + 1;
						break;
					}
				}

				if (0 < index) {
					int length = index + 1;
					byte[] bytes = new byte[length];
					in.get(bytes, 0, length);
					String str = new String(bytes, "UTF-8");
					if (Log.isLoggable(TAG, Log.DEBUG)) {
						Log.d(TAG, ">>>JSON: " + str);
					}
					out.write(str.substring(1, str.length() - 1));
					return true;

				} else {
					return false;
				}
			}
		}

		in.position(in.limit());
		return true;
	}

}
